package com.link.play.fit.ai.ui.main.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.app.ActivityOptionsCompat
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.google.firebase.firestore.Filter
import com.google.gson.Gson
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig.vipNeedPlanPay
import com.link.play.fit.ai.base.BaseFragment
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.base.goToAcForResult
import com.link.play.fit.ai.bean.BaseCalendarData
import com.link.play.fit.ai.bean.ByDesFixBean
import com.link.play.fit.ai.bean.CalendarStatusData
import com.link.play.fit.ai.bean.DesBean
import com.link.play.fit.ai.bean.ExerciseBean
import com.link.play.fit.ai.bean.ExerciseBean.Companion.getMET
import com.link.play.fit.ai.bean.LogWeightBean
import com.link.play.fit.ai.bean.ScanFoodBean
import com.link.play.fit.ai.bean.RecentlyEatenData
import com.link.play.fit.ai.bean.UserGuide
import com.link.play.fit.ai.bean.toCollectFoodInfoData
import com.link.play.fit.ai.bean.toFoodInfoBean
import com.link.play.fit.ai.databinding.FgHomeBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.ext.setThrottleListener
import com.link.play.fit.ai.kv.AuthCache
import com.link.play.fit.ai.kv.AuthCache.isBurnedSwitch
import com.link.play.fit.ai.kv.AuthCache.isFirstShowStreakDialog
import com.link.play.fit.ai.kv.AuthCache.isVip
import com.link.play.fit.ai.kv.AuthCache.timeDay
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_LOG_WEIGHT
import com.link.play.fit.ai.store.CloudStore.DOC_RECENTLY_LIST_DATA
import com.link.play.fit.ai.store.CloudStore.DOC_USER_GUIDE
import com.link.play.fit.ai.store.CloudStore.deleteList
import com.link.play.fit.ai.ui.dialog.HomeStreakDialog
import com.link.play.fit.ai.ui.exercise.DescribeAc
import com.link.play.fit.ai.ui.exercise.RunActivity
import com.link.play.fit.ai.ui.exercise.WeightLiftAc
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.main.MainViewModel
import com.link.play.fit.ai.ui.main.adapter.CalendarAdapter
import com.link.play.fit.ai.ui.main.adapter.HomeChildAdapter
import com.link.play.fit.ai.ui.main.adapter.HomeRecentlyListAdapter
import com.link.play.fit.ai.ui.main.foodDatabase.FoodEditAc
import com.link.play.fit.ai.ui.main.foodDatabase.LogFoodAc
import com.link.play.fit.ai.ui.main.fragment.homeFragment.HomeChildFragment1
import com.link.play.fit.ai.ui.main.setting.SettingAc
import com.link.play.fit.ai.ui.scanFood.FoodDetailAc
import com.link.play.fit.ai.ui.vip.VipFreeAc
import com.link.play.fit.ai.ui.vip.VipRenewAc
import com.link.play.fit.ai.utils.DailyFirstLaunchUtil.isFirstExerciseToday
import com.link.play.fit.ai.utils.DailyFirstLaunchUtil.isFirstLaunchToday
import com.link.play.fit.ai.utils.DateEx.getDayOfMonth
import com.link.play.fit.ai.utils.DateEx.getDayOfMonthByLocal
import com.link.play.fit.ai.utils.GoalUtils.isOverGoal
import com.link.play.fit.ai.utils.GoalUtils.isRatioBelowFivePercent
import com.link.play.fit.ai.utils.WeekDatesUtil.getWeekday
import com.link.play.fit.ai.utils.getExerciseCal
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.time.ZoneId
import java.util.Calendar
import kotlin.math.roundToInt


/**
 *Create by SleepDog on 2025-03-24
 */
class HomeFg : BaseFragment<FgHomeBinding>(FgHomeBinding::inflate) {
    private var recentlyEatenDataList: MutableList<RecentlyEatenData> = mutableListOf()
    private var calendarStatusDataList: MutableList<CalendarStatusData> = mutableListOf()
    private var calendarAdapter: CalendarAdapter? = null

    private var mDatesList: MutableList<CalendarStatusData> = mutableListOf()
    private var mCurrentDayIndex = 0
    private var recentlyListAdapter: HomeRecentlyListAdapter? = null
    private var isFirstRoll = true

    //    private val viewModel: MainViewModel by lazy {
//        ViewModelProvider(requireActivity())[MainViewModel::class.java]
//    }
    private val viewModel: MainViewModel by lazy { (requireActivity() as MainAc).viewModel }
    private val homeFg1 by lazy(LazyThreadSafetyMode.NONE) {
        HomeChildFragment1()
    }
//    private val homeFg2 by lazy(LazyThreadSafetyMode.NONE) {
//        HomeChildFragment2()
//    }
    private val fragmentList: List<Fragment> by lazy(LazyThreadSafetyMode.NONE) {
        mutableListOf(
            homeFg1
        )
    }

    private val homeStreakDialog by lazy {
        activity?.let {
            HomeStreakDialog(it, {
            })
        }

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
//        obserLiveData()
        initData()
        initListener()
        EventBus.getDefault().register(this)

    }

    private fun initListener() {
        binding.homeRightLayout.setThrottleListener {
            homeStreakDialog?.builder()?.show()
        }
//        listOf(binding.rightImg, binding.controlText).forEach {
////            it.setOnClickListener { goToAc(ControlAc::class.java) }
//            it.setOnClickListener { goToAc(WeighControlMethodAc::class.java) }
//        }

        binding.settingImg.setOnClickListener {
                goToAc(SettingAc::class.java){
                    putExtra("data", viewModel.getCalendarData())
                }
//            lifecycleScope.launch {
//                val result = requireActivity().goToAcForResult(
//                    SettingAc::class.java
//                ) {
//                    putExtra("data", viewModel.getCalendarData())
//                }
//                val value = result.data?.getStringExtra("result")
//                "value $value result ${result.data}".d()
//
//                value?.let {
//                    viewModel.onclickTapScan(it)
//                }
//            }
        }
        binding.neigouImg.setOnClickListener {
            lifecycleScope.launch {
                val user = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
                user?.let {
                    if(vipNeedPlanPay){
                        goToAc(VipRenewAc::class.java){
                            putExtra("buyType","controlFg")
                        }
                    }else{
                        goToAc(VipFreeAc::class.java)
                    }
                }
            }
        }
    }

    private fun initData() {

        //timeDay 在每次启动的时候置空,要不食物列表和日历对应不上
        AuthCache.timeDay = ""

        forgeData()
        binding.homeRightText.text = "0"
        binding.homeViewPager.adapter =
            HomeChildAdapter(childFragmentManager, lifecycle, fragmentList)
        setupDots()
        binding.calendarRecyclerView.setHasFixedSize(true)
//         binding.homeRecentlyList.setHasFixedSize(true)
        binding.calendarRecyclerView.layoutManager =
            LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
        binding.homeViewPager.offscreenPageLimit = 2 // 缓存所有页面（适用于少量 Fragment）

        binding.homeViewPager.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                updateDots(position % 2)
            }
        })
    }

    fun isShowNg(isShow: Boolean){
        binding.neigouImg.isVisible = isShow
    }

    fun isShowRecentlyList() {
        if (recentlyEatenDataList.isEmpty()) {
            binding.homeRecentlyList.isVisible = false
            binding.recentlyDesLayout.isVisible = true
            binding.desImg.isVisible = true

        } else {
            binding.homeRecentlyList.isVisible = true
            binding.recentlyDesLayout.isVisible = false
            binding.desImg.isVisible = false
        }
        kotlin.runCatching {
            val p = viewModel.getCalendarPosition()
            val list = viewModel.getDateList()
            if (list.isNotEmpty()) {
                binding.startTrackingText.text = getString(
                    R.string.start_tracking_pic_2, getWeekday(list[p].timeDate, requireActivity())
                )
            } else {
                binding.startTrackingText.text = getString(R.string.start_tracking_pic)
            }
        }
    }

    fun putListData(data: CalendarStatusData, isShow: Boolean = false, isAdjust: Boolean = false) {
        setPrompt(data)
        "putListData data $data".d()
        val index = calendarStatusDataList.indexOfFirst { it.timeDate == data.timeDate }
        if (index != -1) {
            calendarStatusDataList[index] = data
        } else {
            calendarStatusDataList.add(data)
        }
//        viewModel.setDateList(calendarStatusDataList)

        getCalendarList()

        homeFg1.setCalendarData(data)

        var size = 0
        calendarStatusDataList.forEachIndexed { _, calendarStatusData ->
            if (calendarStatusData.consumeCaloriesDaily > 0 || calendarStatusData.consumeProteinDaily > 0 || calendarStatusData.consumeCarbsDaily > 0 || calendarStatusData.consumeFatsDaily > 0) {
                size += 1
            }
        }
        binding.homeRightText.text = "$size"
        homeStreakDialog?.setData(calendarStatusDataList)

        if (!isAdjust) {
            if (isFirstLaunchToday(requireActivity()) || isShow) {
                homeStreakDialog?.builder()?.show()
            }
        }
    }

    fun setListData(list: MutableList<CalendarStatusData>, isShow: Boolean = false) {
        calendarStatusDataList = list

        getCalendarList()
//        calendarStatusDataList.let {
//            homeFg1.setCalendarData(it[it.size - 1])
//        }

        var size = 0
        calendarStatusDataList.forEachIndexed { _, calendarStatusData ->
            if (calendarStatusData.consumeCaloriesDaily > 0 || calendarStatusData.consumeProteinDaily > 0 || calendarStatusData.consumeCarbsDaily > 0 || calendarStatusData.consumeFatsDaily > 0) {
                size += 1
            }
        }
        _binding?.homeRightText?.text = "$size"
//        binding.dkNumText.text = "$size"
        homeStreakDialog?.setData(calendarStatusDataList)
        if (isFirstShowStreakDialog) {
            if (isFirstLaunchToday(requireActivity()) || isShow) {
                homeStreakDialog?.builder()?.show()
            }
            isFirstShowStreakDialog = true

        }

    }

    private fun getCalendarList() {
        lifecycleScope.launch {
            // 生成日期数据并获取当前日期的索引
//            if(mDatesList.isEmpty()){
//                val (datesList, currentDayIndex) = generateDateRange()
//                mDatesList = datesList
//                mCurrentDayIndex = currentDayIndex
//            } android
            val (datesList, currentDayIndex) = generateDateRange()
            if(mDatesList.isEmpty()){
                mDatesList = datesList
            }

            mCurrentDayIndex = currentDayIndex
            val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)

//            mDatesList.forEach {
//                userGuide?.let { user ->
//                    val diff = it.caloriesDaily -user.caloriesDaily
//                    it.differenceDaily = diff
//                }
//            }
            val map = calendarStatusDataList.associateBy { it.timeDate }
            "map  $map".d()
            mDatesList.forEach { item1 ->
                map[item1.timeDate]?.let { item2 ->

//                    item1.caloriesDaily = item2.caloriesDaily + item1.differenceDaily
                    item1.caloriesDaily = item2.caloriesDaily

                    item1.carbsDaily = item2.carbsDaily
                    item1.proteinDaily = item2.proteinDaily
                    item1.fatsDaily = item2.fatsDaily

                    item1.consumeCaloriesDaily = item2.consumeCaloriesDaily
                    item1.consumeCarbsDaily = item2.consumeCarbsDaily
                    item1.consumeProteinDaily = item2.consumeProteinDaily
                    item1.consumeFatsDaily = item2.consumeFatsDaily
                    if (item1.consumeCaloriesDaily > 0 || item1.consumeCarbsDaily > 0 || item1.consumeProteinDaily > 0 || item1.consumeFatsDaily > 0) {
                        item1.isInit = true
                    }
                }
            }

            calendarAdapter = context?.let {
                CalendarAdapter(mDatesList, it) { k, p ->
                    viewModel.setCalendarPosition(p)
                    viewModel.setTimeDay(mDatesList[p].timeDate)
                    timeDay = mDatesList[p].timeDate
                    forgeData(k)
                    viewModel.updateGoalData(
                        caloriesDaily = mDatesList[p].caloriesDaily,
                        carbsDaily = mDatesList[p].carbsDaily,
                        proteinDaily = mDatesList[p].proteinDaily,
                        fatsDaily = mDatesList[p].fatsDaily
                    )
                    val bean = viewModel.getGoalData()
                    "${mDatesList[p].timeDate} mDatesList[p]  ${mDatesList[p]}".d()
                    if (bean.caloriesDaily > 0 || bean.carbsDaily > 0 || bean.proteinDaily > 0 || bean.fatsDaily > 0) {
                        homeFg1.setCalendarData(mDatesList[p])
                    }
                    setPrompt(mDatesList[p])

                }
            }

            binding.calendarRecyclerView.adapter = calendarAdapter
            "mDatesList ${mDatesList}".d()
            viewModel.setDateList(mDatesList)
            if (isFirstRoll) {
                isFirstRoll = false
                binding.calendarRecyclerView.post {
                    if (mCurrentDayIndex != -1) {
                        binding.calendarRecyclerView.smoothScrollToPosition(mCurrentDayIndex)
                        calendarAdapter?.notifyList(mCurrentDayIndex)
                        viewModel.setCalendarPosition(mCurrentDayIndex)
                        viewModel.setTimeDay(mDatesList[mCurrentDayIndex].timeDate)
                        timeDay = mDatesList[mCurrentDayIndex].timeDate
                        homeFg1.setCalendarData(mDatesList[mCurrentDayIndex])
                        setPrompt(mDatesList[mCurrentDayIndex])

                    }
                }
            } else {
                binding.calendarRecyclerView.smoothScrollToPosition(viewModel.getCalendarPosition())
                calendarAdapter?.notifyList(viewModel.getCalendarPosition())
            }

        }
    }


    private fun forgeData(date: String? = getDayOfMonth()) {
        lifecycleScope.launch {
            recentlyEatenDataList = date?.let {
                CloudStore.getList<RecentlyEatenData>(
                    DOC_RECENTLY_LIST_DATA,
                    it
                )
            } as MutableList<RecentlyEatenData>
            recentlyEatenDataList.reverse()
            "recentlyEatenDataList  $recentlyEatenDataList".d()
            binding.homeRecentlyList.layoutManager = LinearLayoutManager(activity)
            recentlyListAdapter =
                HomeRecentlyListAdapter(recentlyEatenDataList, requireActivity()) { it, p, v ->
//                    "recentlyEatenDataList[p].type  ${recentlyEatenDataList[p].type}".d()
                    when (it) {
                        0 -> { //item点击
                            lifecycleScope.launch child@{
                                when (recentlyEatenDataList[p].type) {
                                    1 -> { //运动
                                        var ac: Class<out Activity> = RunActivity::class.java
                                        val data = recentlyEatenDataList[p]

                                        if (data.typeChild == 0) {
                                            ac = RunActivity::class.java
                                        }
                                        if (data.typeChild == 1) {
                                            ac = WeightLiftAc::class.java
                                        }
                                        if (data.typeChild == 3) {
                                            ac = DescribeAc::class.java
                                        }
                                        val result = requireActivity().goToAcForResult(ac) {
                                            putExtra("data", data)
                                        }
                                        val exerciseBean: ExerciseBean? =
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                                result.data?.getSerializableExtra(
                                                    "Exercise",
                                                    ExerciseBean::class.java
                                                )
                                            } else {
                                                @Suppress("DEPRECATION")
                                                (result.data?.getSerializableExtra("Exercise") as ExerciseBean?)
                                            }
                                        "exerciseBean $exerciseBean".d()
                                        exerciseBean?.let {
                                            val kg = CloudStore.getListItem<LogWeightBean>(
                                                DOC_LOG_WEIGHT,
                                                DOC_LOG_WEIGHT,
                                                Filter.lessThanOrEqualTo(
                                                    "createTime",
                                                    System.currentTimeMillis()
                                                )
                                            )?.weightKg ?: viewModel.recentlyGoalData.value.weightKg

                                            val cal = getExerciseCal(
                                                it.getMET(),
                                                kg,
                                                it.time.toFloat() / 60f
                                            )
                                            val list = viewModel.getDateList()
                                            val num = viewModel.getCalendarPosition()
                                            if(it.modify == -1){ //删除
                                                "isBurnedSwitchV ${recentlyEatenDataList[p].isBurnedSwitchV} isBurnedSwitch $isBurnedSwitch it.modify  ${it.modify } cal $cal  list[num].caloriesDaily ${list[num].caloriesDaily}".d()
                                                if(recentlyEatenDataList[p].isBurnedSwitchV){
//                                                if (isBurnedSwitch) {
                                                    list[num].caloriesDaily -= recentlyEatenDataList[p].caloriesDaily
                                                    list[num].exerciseCaloriesDaily -= recentlyEatenDataList[p].caloriesDaily
                                                    putListData(
                                                        list[num],
                                                        isFirstExerciseToday(requireActivity()),
                                                        isAdjust = true
                                                    )
                                                    "list[num].caloriesDaily ${list[num].caloriesDaily}".d()
                                                    viewModel.putCalendarListData(oldData = list[num])
                                                }
                                                kotlin.runCatching {
                                                    deleteList(
                                                        DOC_RECENTLY_LIST_DATA,
                                                        recentlyEatenDataList[p].timeDay,
                                                        recentlyEatenDataList[p].createTime
                                                    )
                                                    recentlyEatenDataList.removeAt(p)
                                                    recentlyListAdapter?.notifyItemRemoved(p)
                                                    isShowRecentlyList()
                                                }
                                            }else{
                                                if (isBurnedSwitch) {
//                                                    if(recentlyEatenDataList[p].isBurnedSwitchV){
                                                        list[num].caloriesDaily -= recentlyEatenDataList[p].caloriesDaily
                                                        list[num].caloriesDaily += cal
                                                        putListData(
                                                            list[num],
                                                            isFirstExerciseToday(requireActivity()),
                                                            isAdjust = true
                                                        )
                                                        viewModel.putCalendarListData(oldData = list[num])
//                                                    }
                                                }
                                                recentlyEatenDataList[p] =
                                                    recentlyEatenDataList[p].copy(
                                                        intensityPercent = it.intensityPercent,
                                                        time = it.time, describe = it.describe,
                                                        caloriesDaily = cal
                                                    )
                                                "recentlyEatenDataList ${recentlyEatenDataList[p]}".d()
                                                recentlyListAdapter?.notifyItemChanged(p)
                                                if (it.type == 3) {
                                                    viewModel.byDescribe(
                                                        DesBean(
                                                            description = it.describe,
                                                            weight = kg
                                                        ), data.createTime
                                                    )
                                                } else {
                                                    viewModel.saveRecentlyData(recentlyEatenDataList[p])
                                                }
                                            }


                                        }
                                    }

                                    2 -> {  //扫描的食物类型

                                        val result = requireActivity().goToAcForResult(
                                            FoodDetailAc::class.java,
                                            ActivityOptionsCompat.makeSceneTransitionAnimation(
                                                requireActivity(),
                                                v, v.transitionName
                                            )
                                        ) {
                                            putExtra(
                                                "recentlyEatenData",
                                                recentlyEatenDataList[p]
                                            )
                                            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) // 授予读取权限
                                        }
                                        val resultData =
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                                result.data?.getSerializableExtra(
                                                    "recentlyEatenData",
                                                    RecentlyEatenData::class.java
                                                )
                                            } else {
                                                @Suppress("DEPRECATION")
                                                (result.data?.getSerializableExtra("recentlyEatenData") as RecentlyEatenData?)
                                            } ?: return@child

                                        updateReturnData(p, resultData)
                                    }

                                    3 -> { //自定义食物
                                        val result =
                                            (requireActivity() as MainAc).goToAcForResult(LogFoodAc::class.java) {
                                                putExtra(
                                                    "bean",
                                                    recentlyEatenDataList[p].toCollectFoodInfoData()
                                                )
                                            }
                                        val resultData =
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                                result.data?.getSerializableExtra(
                                                    "recentlyEatenData",
                                                    RecentlyEatenData::class.java
                                                )
                                            } else {
                                                @Suppress("DEPRECATION")
                                                (result.data?.getSerializableExtra("recentlyEatenData") as RecentlyEatenData?)
                                            } ?: return@child

                                        updateReturnData(p, resultData)
                                    }

                                    4 -> { //接口搜索到的食物
                                        val result = requireActivity().goToAcForResult(
                                            FoodEditAc::class.java
                                        ) {
                                            putExtra(
                                                FoodEditAc.Bean,
                                                recentlyEatenDataList[p].toFoodInfoBean()
                                            )
                                            putExtra(FoodEditAc.IntentParamsSearch, false)
                                        }
                                        val resultData =
                                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                                result.data?.getSerializableExtra(
                                                    "recentlyEatenData",
                                                    RecentlyEatenData::class.java
                                                )
                                            } else {
                                                @Suppress("DEPRECATION")
                                                (result.data?.getSerializableExtra("recentlyEatenData") as RecentlyEatenData?)
                                            } ?: return@child
                                        val mutValue = result.data?.extras?.getInt("mulValue") ?: 1
                                        "mutValue=$mutValue resultData=$resultData".d()

                                        updateReturnData(p, resultData)
                                    }
                                }
                            }
                        }

                        1 -> { //重新拍照
                            viewModel.onclickTapScan("scanAgain")
                        }

                        2 -> { //删除
                            kotlin.runCatching {
                                deleteList(
                                    DOC_RECENTLY_LIST_DATA,
                                    recentlyEatenDataList[p].timeDay,
                                    recentlyEatenDataList[p].createTime
                                )
                                recentlyEatenDataList.removeAt(p)
                                recentlyListAdapter?.notifyItemRemoved(p)
                                isShowRecentlyList()
                            }
                        }
                    }
                }
            binding.homeRecentlyList.adapter = recentlyListAdapter
            isShowRecentlyList()
        }
    }

    //更新详情返回来的数据 4556 108 54
    private fun updateReturnData(p: Int, recentlyEatenData: RecentlyEatenData? = null) {
        "recentlyEatenData  $recentlyEatenData".d()
        recentlyEatenData?.let {
            //更新日历数据
            val list = viewModel.getDateList()
            val num = viewModel.getCalendarPosition()
            list[num].consumeCaloriesDaily -= (recentlyEatenDataList[p].caloriesDaily * recentlyEatenDataList[p].servings).roundToInt()
            list[num].consumeCarbsDaily -= (recentlyEatenDataList[p].carbsDaily * recentlyEatenDataList[p].servings).roundToInt()
            list[num].consumeProteinDaily -= (recentlyEatenDataList[p].proteinDaily * recentlyEatenDataList[p].servings).roundToInt()
            list[num].consumeFatsDaily -= (recentlyEatenDataList[p].fatsDaily * recentlyEatenDataList[p].servings).roundToInt()
            //更新首页列表数据
            recentlyEatenDataList[p] = it
            recentlyListAdapter?.notifyItemChanged(p)
            viewModel.saveRecentlyData(it)
            list[num].consumeCaloriesDaily += (it.caloriesDaily * it.servings).roundToInt()
            list[num].consumeCarbsDaily += (it.carbsDaily * it.servings).roundToInt()
            list[num].consumeProteinDaily += (it.proteinDaily * it.servings).roundToInt()
            list[num].consumeFatsDaily += (it.fatsDaily * it.servings).roundToInt()

            putListData(
                list[num],
                isFirstExerciseToday(requireActivity())
            )
            viewModel.putCalendarListData(oldData = list[num])

        }
    }

    fun addRecentlyList(data: RecentlyEatenData) {
        recentlyEatenDataList.add(0, data)
        recentlyListAdapter?.notifyItemInserted(0)
        isShowRecentlyList()
    }

    fun deleteRecentlyList(data: RecentlyEatenData) {
        var index = -1
        for ((i, v) in recentlyEatenDataList.withIndex()) {
            if (v.createTime == data.createTime) {
                index = i
            }
        }
        if (index != -1) {
            recentlyEatenDataList.removeAt(index)
            recentlyListAdapter?.notifyItemRemoved(index)
        }
        isShowRecentlyList()
        setPrompt()
    }

    fun updateRecentlyList(data: RecentlyEatenData) {
        var index = -1
        for ((i, v) in recentlyEatenDataList.withIndex()) {
            if (v.createTime == data.createTime) {
                index = i
            }
        }
        if (index != -1) {
            recentlyEatenDataList[index] = data
            recentlyListAdapter?.notifyItemChanged(index)
            viewModel.saveRecentlyData(recentlyEatenDataList[index])
        }
        setPrompt()
    }

    fun notifyRecentlyByDes(data: ByDesFixBean? = null, tempId: String? = null, weight: Int) {
        tempId?.let {
            val index = recentlyEatenDataList.indexOfFirst { it.createTime == tempId }
            if(index == -1) return@let
            if (data != null) {
                val cal =
                    getExerciseCal(data.metRate.toFloat(), weight, data.duration.toFloat() / 60f)
                recentlyEatenDataList[index] = recentlyEatenDataList[index].copy(
                    showType = 1,
                    caloriesDaily = cal,
                    metRate = data.metRate,

                    name = data.name,
                    intensityPercent = (data.intensity * 10).roundToInt(),
                    time = data.duration.roundToInt(),
                    )
                val p = viewModel.getCalendarPosition()
                val list = viewModel.getDateList()
                if (isBurnedSwitch) {
                    list[p].caloriesDaily += cal
                    list[p].exerciseCaloriesDaily += cal
                    putListData(list[p], isFirstExerciseToday(requireActivity()), isAdjust = true)
                }
                viewModel.putCalendarListData(oldData = list[p])
            } else {
                recentlyEatenDataList[index] = recentlyEatenDataList[index].copy(
                    showType = 1
                )
            }
            viewModel.saveRecentlyData(recentlyEatenDataList[index])
            recentlyListAdapter?.notifyItemChanged(index)
        }
    }

    fun notifyRecentlyScanLoadItem(data: ScanFoodBean? = null, tempId: String? = null) {
        tempId?.let {
            val index = recentlyEatenDataList.indexOfFirst { it.createTime == tempId }
            if (index != -1) {
                if (data != null) {
                    var ingredients = ""
                    data.ingredients?.let {
                        ingredients = Gson().toJson(it)
                    }

                    "data.ingredients ${data.ingredients}".d()
                    recentlyEatenDataList[index] = recentlyEatenDataList[index].copy(
                        foodName = data.foodName,
                        healthComment = data.healthComment,
                        healthScore = data.healthScore,
                        ingredients = ingredients
                    )

                    if (data.nutrition == null) {
                        recentlyEatenDataList[index] = recentlyEatenDataList[index].copy(
                            showType = 3
                        )
                    } else {
                        data.nutrition.let {
                            if (it.caloriesKcal > 0) {
                                recentlyEatenDataList[index] = recentlyEatenDataList[index].copy(
                                    showType = 1,
                                    caloriesDaily = it.caloriesKcal,
                                    carbsDaily = it.carbsG,
                                    proteinDaily = it.proteinG,
                                    fatsDaily = it.fatsG,
                                )
                            } else {
                                recentlyEatenDataList[index] = recentlyEatenDataList[index].copy(
                                    showType = 3
                                )
                            }
                        }
                    }
                } else {
                    recentlyEatenDataList[index] = recentlyEatenDataList[index].copy(
                        showType = 3
                    )
                }
                viewModel.saveRecentlyData(recentlyEatenDataList[index])
                recentlyListAdapter?.notifyItemChanged(index)
            }
        }
    }


    private suspend fun generateDateRange(): Pair<MutableList<CalendarStatusData>, Int> {
        val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)

        val calendar = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
//        val dates = mutableListOf<Date>()
        val calendarList: MutableList<CalendarStatusData> = mutableListOf()
        var currentDayIndex = -1
        kotlin.runCatching {
            val today = calendar.time

            val tomorrow = calendar.clone() as Calendar
            tomorrow.add(Calendar.DAY_OF_MONTH, 1)

            // 计算28天前的日期
            val twentyEightDaysAgo = calendar.clone() as Calendar
            twentyEightDaysAgo.add(Calendar.DAY_OF_MONTH, -26)

            // 重置到起始日期（28天前）
            val startDate = twentyEightDaysAgo.clone() as Calendar
            val endDate = tomorrow.timeInMillis

            while (startDate.timeInMillis <= endDate) {
                val localDate = startDate.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate()
                val date = startDate.time

                val calendarStatusData = CalendarStatusData(
                    date = startDate.time,
                    timeDate = getDayOfMonthByLocal(localDate),
                    caloriesDaily = userGuide?.caloriesDaily ?: 0,
                    carbsDaily = userGuide?.carbsDaily ?: 0,
                    proteinDaily = userGuide?.proteinDaily ?: 0,
                    fatsDaily = userGuide?.fatsDaily ?: 0,
                )
                calendarList.add(calendarStatusData)
                // 检查是否是今天
                if (date.date == today.date) {
                    currentDayIndex = calendarList.size - 1
                }
                startDate.add(Calendar.DAY_OF_MONTH, 1)
            }

        }
        return Pair(calendarList, currentDayIndex)

    }

    private fun setupDots() {
        val dots = arrayOfNulls<ImageView>(2)
        binding.dotsContainer.removeAllViews()
        for (i in 0 until 2) {
            dots[i] = ImageView(activity).apply {
                setImageResource(R.drawable.dot_unselected)
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    setMargins(10, 0, 10, 0)
                }
            }
            binding.dotsContainer.addView(dots[i])
        }
        // 默认选中第一个圆点
        if (dots.isNotEmpty()) {
            dots[0]?.setImageResource(R.drawable.dot_selected)
        }
    }

    private fun updateDots(position: Int) {
        for (i in 0 until binding.dotsContainer.childCount) {
            val dot = binding.dotsContainer.getChildAt(i) as ImageView
            dot.setImageResource(
                if (i == position) R.drawable.dot_selected else R.drawable.dot_unselected
            )
        }
    }

    private var mPromptList:MutableList<String> = mutableListOf()
    @SuppressLint("StringFormatMatches")
    private fun setPrompt(data: CalendarStatusData?=null) {
        "setPrompt  $data".d()
        var calendarData = if(data == null){
            val p = viewModel.getCalendarPosition()
            val list = viewModel.getDateList()
            list[p]
        }else{
            data
        }

        lifecycleScope.launch {

            mPromptList.clear()
            val total = calendarData.carbsDaily + calendarData.fatsDaily + calendarData.proteinDaily
            if (isRatioBelowFivePercent(calendarData.consumeCarbsDaily, total,5)) {
                mPromptList.add(getString(R.string.meal_suggestion2_carbs))
            }
            if (isRatioBelowFivePercent(calendarData.consumeFatsDaily, total,5)) {
                mPromptList.add(getString(R.string.meal_suggestion2_fat))

            }
            if (isRatioBelowFivePercent(calendarData.consumeProteinDaily, total,5)) {
                mPromptList.add(getString(R.string.meal_suggestion2_protein))
            }
            val userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            userGuide?.let {
                "goal ${it.goal}".d()
                when (it.goal) {
                    0 -> {
                        if (isOverGoal(calendarData.consumeCarbsDaily, total, 55)) {
                            mPromptList.add(getString(R.string.meal_suggestion1_carbs))
                        }
                        if (isOverGoal(calendarData.consumeFatsDaily, total, 20)) {
                            mPromptList.add(getString(R.string.meal_suggestion1_fat))

                        }
                        if (isOverGoal(calendarData.consumeProteinDaily, total, 25)) {
                            mPromptList.add(getString(R.string.meal_suggestion1_protein))
                        }
                    }

                    1 -> {
                        if (calendarData.consumeCarbsDaily > calendarData.carbsDaily) {
                            mPromptList.add(getString(
                                R.string.meal_suggestion3_carbs,
                                calendarData.carbsDaily,
                                calendarData.consumeCarbsDaily
                            ))

                        }
                        if (calendarData.consumeFatsDaily > calendarData.fatsDaily) {
                            mPromptList.add(
                                getString(
                                    R.string.meal_suggestion3_fat,
                                    calendarData.fatsDaily,
                                    calendarData.consumeFatsDaily
                                )
                            )
                        }
                        if (calendarData.consumeProteinDaily > calendarData.proteinDaily) {
                            mPromptList.add(
                                getString(
                                    R.string.meal_suggestion3_protein,
                                    calendarData.proteinDaily,
                                    calendarData.consumeProteinDaily
                                )
                            )
                        }
                    }

                    2 -> {
                        if (isOverGoal(calendarData.consumeCarbsDaily, total, 45)) {
                            mPromptList.add(getString(R.string.meal_suggestion1_carbs))
                        }
                        if (isOverGoal(calendarData.consumeFatsDaily, total, 25)) {
                            mPromptList.add(getString(R.string.meal_suggestion1_fat))
                        }
                        if (isOverGoal(calendarData.consumeProteinDaily, total, 30)) {
                            mPromptList.add(getString(R.string.meal_suggestion1_protein))
                        }
                    }
                }
            }
            showPromptTips()
        }
    }

    private fun showPromptTips(){
        binding.promptLayout.isVisible = mPromptList.isNotEmpty() == true

        binding.promptText.setData(mPromptList)
        binding.promptText.startAutoScroll()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: BaseCalendarData) {
        "homefg onMessageEvent ${event.data}".d()
        updateUserTarget(event.data)
        viewModel.updateFlushControlLiveData("flushControl")
    }

    /**
     * 更新用户目标值
     */
    @SuppressLint("NotifyDataSetChanged")
     fun updateUserTarget(data: CalendarStatusData){
        setPrompt(data)
        "putListData data $data".d()
        val index = calendarStatusDataList.indexOfFirst { it.timeDate == data.timeDate }

        lifecycleScope.launch {
            val user = CloudStore.get<UserGuide>(DOC_USER_GUIDE)

            user?.let {
                mDatesList.forEachIndexed { _, calendarStatusData ->
                    calendarStatusData.caloriesDaily = it.caloriesDaily + calendarStatusData.exerciseCaloriesDaily
                    calendarStatusData.carbsDaily = it.carbsDaily
                    calendarStatusData.proteinDaily = it.proteinDaily
                    calendarStatusData.fatsDaily = it.fatsDaily
                }
                calendarAdapter?.notifyDataSetChanged()
                viewModel.setDateList(mDatesList)

                val p = viewModel.getCalendarPosition()
                if (index != -1) {
                    calendarStatusDataList[index] = (mDatesList[p])
                }
                "index $index  mDatesList ${mDatesList[p]} ".d()

                homeStreakDialog?.setData(calendarStatusDataList)
                homeFg1.setCalendarData(mDatesList[p])
                viewModel.putCalendarListData(mDatesList[p])
            }
        }
    }


    fun toPlanUpdateData(){
        lifecycleScope.launch {
            val  userGuide = CloudStore.get<UserGuide>(DOC_USER_GUIDE)
            val p = viewModel.getCalendarPosition()
            val list = viewModel.getDateList()
            userGuide?.let {
                list[p].caloriesDaily = it.caloriesDaily
                list[p].carbsDaily = it.carbsDaily
                list[p].proteinDaily = it.proteinDaily
                list[p].fatsDaily = it.fatsDaily
            }

            calendarAdapter?.notifyItemChanged(p)
            viewModel.putCalendarListData(oldData = list[p])
            putListData(list[p], isFirstExerciseToday(requireActivity()), isAdjust = true)
        }

    }

}